package szf.im.server.util;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;

/**
 * @author shizhanfu
 * zk帮助类
 */
public class ZkClient {
    private static CuratorFramework client;

    private ZkClient() {
    }

    public static CuratorFramework getInstance(String url) {
        if (client == null) {
            synchronized (ZkClient.class) {
                if (client == null) {
                    RetryPolicy retryPolicy = new RetryNTimes(10, 10);
                    client = CuratorFrameworkFactory.builder().connectString(url)
                            .connectionTimeoutMs(30)
                            .retryPolicy(retryPolicy)
                            .build();
                    client.start();
                }
            }
        }
        return client;
    }

    public static boolean CreateNode(String path, String val) throws Exception {
        String s = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, val.getBytes());
        System.out.println("注册成功:" + s);
        return true;
    }
}